import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-05-29
 * Time: 21:49
 */
public class MyArrayList {
    public int[] elem;
    public int useSize;
    public static final int DEFAULT_SIZE = 5;

    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }

    //在数组末尾添加
    public void Add(int data) {
        //检查数组是否需要扩容
        if (is_Full()) {
            resize();
        }
        this.elem[this.useSize] = data;
        this.useSize++;
    }

    private boolean is_Full() {
        if (this.elem.length == this.useSize) {
            return true;
        }
        return false;
    }

    public void resize() {
        this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
    }

    public void checkIndex(int pos) {
        if (pos < 0 || pos > this.useSize) {
            throw new IndexOutOfException("数组下标异常，请检查一下!");
        }
    }

    //在pos位置放置
    public void Add(int pos, int data) {
        //判断pos位置是否合法
        checkIndex(pos);
        //判断是否需要扩容
        if (is_Full()) {
            resize();
        }
        for (int i = this.useSize - 1; i >= pos; i--) {
            this.elem[i + 1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.useSize++;
    }
    public int indexOf(int toFind){
        for(int i=0;i<this.useSize;i++){
            if(this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }
    //判断是覅有含有某个元素
    public boolean contains(int toFind){
        //找到下标
        int index = this.indexOf(toFind);
        if(index == -1){
            return false;
        }
        return true;
    }
    public void checkgetIndex(int pos){
        if(pos <0 || pos>=this.useSize){
            throw new IndexOutOfException("pos位置不合法,请检查pos位置的合法性!");
        }
    }
    //获取pos位置的元素
    public int get(int pos){
        //判断pos是否合法
        checkgetIndex(pos);
        return this.elem[pos];
    }

    public void display(){
        for(int i=0;i<this.useSize;i++){
            System.out.print(this.elem[i]+" ");
        }
        System.out.println();
    }

    public void set(int pos,int value){
        checkgetIndex(pos);
        //将pos位置的值设置为value
        this.elem[pos] = value;
    }

    //删除第一次出现的关键字value
    public void remove(int toRemove){
        int index = indexOf(toRemove);
        if(index == -1){
            return;
        }
        //从前往后覆盖
        for(int i = index;i<this.useSize-1;i++){
            this.elem[i] = this.elem[i+1];
        }
        this.useSize--;
        //如果是引用类型
        //this.elem[this.useSize] = null;
    }
    public int size(){
        return this.useSize;
    }
    public void clear(){
        this.useSize=0;
        //引用类型还有遍历置空
    }
}
